<template>
  <el-config-provider :locale="zhCn">
    <div class="script-approva">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="success" :disabled="selectedRowKeys.length === 0" @click="handleApprove">批量通过审批</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="dataList" border style="width: 100%" v-loading="loading" class="custom-table" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="issue" label="问题" min-width="200" />
          <el-table-column prop="answer" label="答案" min-width="200" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default>
              <el-tag type="warning">审核中</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createByStr" label="创建人" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleSingleApprove(scope.row)">通过审批</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getAIModelList } from '@/api/privateModel/aiTrain';
import { approveScript } from '@/api/companyMange/scriptApprova';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

interface LanguageSkill {
  id: number;
  accountType: string;
  aiModelId: number;
  issue: string;
  answer: string;
  status: string;
  reviewer?: string;
  createBy: string;
  createTime: string;
  updateBy?: string;
  updateTime?: string;
  excelId?: string;
  vectorId?: string;
}

// 筛选表单
const filterForm = reactive({
  issue: '',
  answer: ''
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '问题',
    prop: 'issue',
    type: 'input',
    placeholder: '请输入问题'
  },
  {
    label: '答案',
    prop: 'answer',
    type: 'input',
    placeholder: '请输入答案'
  }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dataList = ref<LanguageSkill[]>([]);
const loading = ref(false);
const selectedRowKeys = ref<number[]>([]);

// 查询方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  try {
    const searchData = formData || filterForm;
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      status: '0',
      ...(searchData.issue ? { issue: searchData.issue } : {}),
      ...(searchData.answer ? { answer: searchData.answer } : {})
    };
    const res = await getAIModelList(params);
    if (res.code === 200) {
      dataList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error('获取数据失败');
    }
  } catch (error) {
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  filterForm.issue = '';
  filterForm.answer = '';
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 多选
const handleSelectionChange = (rows: LanguageSkill[]) => {
  selectedRowKeys.value = rows.map((row) => row.id);
};

// 批量审批
const handleApprove = async () => {
  if (selectedRowKeys.value.length === 0) return;
  try {
    await ElMessageBox.confirm('确定要通过选中话术的审批吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const ids = selectedRowKeys.value.join(',');
    const res = await approveScript(ids);
    if (res.code === 200) {
      ElMessage.success('审批通过成功');
      handleSearch();
      selectedRowKeys.value = [];
    } else {
      ElMessage.error(res?.data?.msg || '审批失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('审批失败');
    }
  }
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.issue = val.issue || '';
  filterForm.answer = val.answer || '';
};

// 单条审批
const handleSingleApprove = async (row: LanguageSkill) => {
  try {
    await ElMessageBox.confirm('确定要通过该话术的审批吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const res = await approveScript(row.id.toString());
    if (res.code === 200) {
      ElMessage.success('审批通过成功');
      handleSearch();
    } else {
      ElMessage.error(res?.data?.msg || '审批失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('审批失败');
    }
  }
};

// 初始化
onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped>
.script-approva {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }
}
</style>
